package com.loe.ktui

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.Drawable
import android.util.TypedValue
import android.view.View
import android.widget.ImageView
import androidx.annotation.DrawableRes
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.Target

inline val String.ktColor: Int
    get()
    {
        return try
        {
            Color.parseColor(this)
        } catch (e: Exception)
        {
            0
        }
    }

/** Glide配置 */
val GLIDE_OPTION = RequestOptions().diskCacheStrategy(DiskCacheStrategy.ALL).timeout(10000)

/** url图预加载 */
fun String.preLoad(context: Context)
{
    Glide.with(context)
        .setDefaultRequestOptions(GLIDE_OPTION)
        .load(this)
        .preload()
}

fun Bitmap.crop(xRate: Double, yRate: Double, wRate: Double, hRate: Double): Bitmap
{
    val x = (xRate * width + 0.5).toInt()
    val y = (yRate * height + 0.5).toInt()
    val w = (wRate * width + 0.5).toInt()
    val h = (hRate * height + 0.5).toInt()
    return Bitmap.createBitmap(this, x, y, w, h)
}

fun String.preLoadBitmap(context: Context, ok: (resource: Bitmap) -> Unit)
{
    Glide.with(context)
        .setDefaultRequestOptions(GLIDE_OPTION)
        .asBitmap()
        .load(this)
        .listener(object : RequestListener<Bitmap>
        {
            override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Bitmap>?, isFirstResource: Boolean): Boolean
            {
                return false
            }

            override fun onResourceReady(resource: Bitmap?, model: Any?, target: Target<Bitmap>?, dataSource: DataSource?, isFirstResource: Boolean): Boolean
            {
                resource?.let()
                { bitmap ->
                    ok(bitmap)
                    return true
                }
                return false
            }
        })
        .preload()
}

/** url图加载回调 */
fun String.preLoadCallback(context: Context, ok: (resource: Drawable) -> Unit)
{
    try
    {
        Glide.with(context)
            .setDefaultRequestOptions(GLIDE_OPTION)
            .load(this)
            .listener(object : RequestListener<Drawable>
            {
                override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Drawable>?, isFirstResource: Boolean): Boolean
                {
                    return false
                }

                override fun onResourceReady(resource: Drawable?, model: Any?, target: Target<Drawable>?, dataSource: DataSource?, isFirstResource: Boolean): Boolean
                {
                    if (resource != null) ok(resource)
                    return true
                }
            }).preload()
    } catch (e: Exception)
    {
    }
}

/** String转图片 */
fun Context.getUrlDrawable(url: String, ok: (resource: Drawable) -> Unit)
{
    ktSafe()
    {
        when
        {
            url.startsWith("http") || url.startsWith("file:") -> url.preLoadCallback(this, ok)
            url.startsWith("/") -> (KtUi.baseUrl + url).preLoadCallback(this, ok)
            url.startsWith("#") -> ok(ColorDrawable(url.ktColor))
            else ->
            {
                ok(resources.getDrawable(resources.getIdentifier(url, "mipmap", packageName), theme))
            }
        }
    }
}

fun View.setBgRipple() = with(TypedValue())
{
    context.theme.resolveAttribute(android.R.attr.selectableItemBackground, this, true)
    setBackgroundResource(resourceId)
}

fun View.setBgCircleRipple() = with(TypedValue())
{
    context.theme.resolveAttribute(android.R.attr.selectableItemBackgroundBorderless, this, true)
    setBackgroundResource(resourceId)
}

/********************************************************** 背景 ************************************************************/

/** 背景图url */
inline var View.bgUrl
    get() = ""
    set(value)
    {
        value.preLoadCallback(context)
        {
            background = it
        }
    }

/** 背景图res名称，在mipmap文件里配置 */
inline var View.bgName
    get() = ""
    set(value)
    {
        try
        {
            setBackgroundResource(context.resources.getIdentifier(value, "mipmap", context.packageName))
        } catch (e: Exception)
        {
        }
    }

/** 背景颜色 */
inline var View.bgColor
    get() = ""
    set(value)
    {
        setBackgroundColor(value.ktColor)
    }

/** 背景 */
inline var View.bg
    get() = ""
    set(value)
    {
        when
        {
            value.startsWith("http") || value.startsWith("file:") -> bgUrl = value
            value.startsWith("/") -> bgUrl = KtUi.baseUrl + value
            value.startsWith("#") -> bgColor = value
            value == BG_RIPPLE -> setBgRipple()
            value == BG_RIPPLE_CIRCLE -> setBgCircleRipple()
            value == BG_RIPPLE_WHITE -> setBackgroundResource(R.drawable.kt_ripple_item_bg)
            else -> bgName = value
        }
    }

/** 水波纹背景 */
const val BG_RIPPLE = "ripple"

/** 圆形水波纹背景 */
const val BG_RIPPLE_CIRCLE = "rippleCircle"

/** 白色水波纹背景 */
const val BG_RIPPLE_WHITE = "rippleWhite"

/********************************************************** 图片 ************************************************************/

/** 图片url */
fun ImageView.setSrcUrl(url: String, @DrawableRes def: Int? = null)
{
    if(this is KtImageView)
    {
        if(url.startsWith("file:"))
        {
            pathString = url
        }else
        {
            urlString = url
        }
    }
    Glide.with(this)
        .setDefaultRequestOptions(GLIDE_OPTION)
        .load(url)
        .placeholder(def ?: R.mipmap.kt_default_load)
        .error(def ?: R.mipmap.kt_default_error)
        .into(this)
}

/** 图片url */
inline var ImageView.srcUrl
    get() = if(this is KtImageView) urlString else ""
    set(value)
    {
        if(this is KtImageView)
        {
            if(value.startsWith("file:"))
            {
                pathString = value
            }else
            {
                urlString = value
            }
        }
//        value.preLoadCallback(context)
//        {
//            setImageDrawable(it)
//        }

        Glide.with(this)
            .setDefaultRequestOptions(GLIDE_OPTION)
            .load(value)
            .dontAnimate()
            .placeholder(R.mipmap.kt_default_load)
            .error(R.mipmap.kt_default_error)
            .into(this)
    }

/** 图片res名称，在mipmap文件里配置 */
inline var ImageView.srcName
    get() = ""
    set(value)
    {
        try
        {
            if(value.isNotBlank()) setImageResource(context.resources.getIdentifier(value, "mipmap", context.packageName))
        } catch (e: Exception)
        {
        }
    }

/** 图片颜色 */
inline var ImageView.srcColor
    get() = ""
    set(value)
    {
        setImageDrawable(ColorDrawable(value.ktColor))
    }

/** 图片 */
inline var ImageView.src
    get() = ""
    set(value)
    {
        when
        {
            value.startsWith("http") || value.startsWith("file:") -> srcUrl = value
            value.startsWith("/") -> srcUrl = KtUi.baseUrl + value
            value.startsWith("#") -> srcColor = value
            else -> srcName = value
        }
    }

/** 图片（有加载图） */
fun ImageView.setSrc(url: String, @DrawableRes def: Int? = null)
{
    when
    {
        url.startsWith("http") || url.startsWith("file:") -> setSrcUrl(url, def)
        url.startsWith("/") -> setSrcUrl(KtUi.baseUrl + url, def)
        url.startsWith("#") -> srcColor = url
        url.isEmpty() -> setImageResource(def ?: R.mipmap.kt_default_load)
        else -> srcName = url
    }
}